const Router = require("koa-router");
const { Auth } = require("@middlewares/auth");
const { Rebate, RebateRecord } = require("@models/rebate");
const { User } = require("@models/user");
const { Op, where } = require("sequelize");
const { sequelize } = require("@core/db");
const router = new Router({
  prefix: "/admin/rebate",
});

// 获取回扣列表
router.post("/list", new Auth(16).m, async (ctx, next) => {
  const { page = 1, pageSize = 10, uid, settle } = ctx.request.body;
  const offset = (page - 1) * pageSize;
  const where = { pid: uid, deleted_at: settle ? { [Op.ne]: null } : null };
  const count_money = await Rebate.findAll({
    where: { pid: uid },
    attributes: [
      [sequelize.fn("SUM", sequelize.col("rebate_money")), "count_money"],
    ],
  });
  const { count: total, rows } = await Rebate.findAndCountAll({
    where,
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [["created_at", "desc"]],
    include: [
      {
        model: User,
        required: false,
      },
    ],
    paranoid: false,
  });
  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    count_money: count_money[0],
    data: rows,
  };
});

//回扣结算
router.post("/settle", new Auth(16).m, async (ctx, next) => {
  const { uid, count_money } = ctx.request.body;
  // 创建结算记录
  const rr = await RebateRecord.create({
    uid,
    rr_money: count_money,
  });
  // 更新回扣记录结算id
  await Rebate.update({ rr_id: rr.rr_id }, { where: { pid: uid } });
  // 删除所有回扣
  await Rebate.destroy({ where: { pid: uid } });
  ctx.body = {
    code: 200,
    msg: "结算成功",
  };
});

// 查询结算记录
router.post("/rr/list", new Auth(16).m, async (ctx, next) => {
  const { page = 1, pageSize = 10, uid } = ctx.request.body;
  const offset = (page - 1) * pageSize;
  const count_money = await Rebate.findAll({
    where: { uid: uid },
    attributes: [
      [sequelize.fn("SUM", sequelize.col("rebate_money")), "count_money"],
    ],
  })[0];
  const { count: total, rows } = await RebateRecord.findAndCountAll({
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [["created_at", "desc"]],
    where: { uid },
    paranoid: false,
  });
  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    count_money: count_money,
    data: rows,
  };
});

// 结算记录详情
router.post("/rr/detail_list", new Auth(16).m, async (ctx, next) => {
  const { rr_id, page = 1, pageSize = 10 } = ctx.request.body;
  const offset = (page - 1) * pageSize;
  // 查询回扣详情列表
  const { count: total, rows } = await Rebate.findAndCountAll({
    where: { rr_id },
    limit: pageSize, // 每页数量
    order: [["created_at", "desc"]],
    include: [
      {
        model: User,
        required: false,
      },
    ],
    offset, // 偏移量
    paranoid: false,
  });
  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows,
  };
});

module.exports = router;
